package com.xiaolu.qqclient.test;

import com.xiaolu.qqclient.service.ManageClientConnectServerThread;
import com.xiaolu.qqclient.view.ChatRoomGUI;
import com.xiaolu.qqcommon.Message;
import com.xiaolu.qqcommon.MessageType;

import javax.sound.sampled.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

public class AudioClient {

    private boolean recording = false;
    private ByteArrayOutputStream audioData;
    private TargetDataLine line;


    public void startRecording() {
        if (recording) {
            System.out.println("已经在录音中...");
            return;
        }

        recording = true;
        audioData = new ByteArrayOutputStream();

        new Thread(() -> {
            try {
                // 配置音频格式
                AudioFormat format = new AudioFormat(44100, 16, 2, true, true);
                DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
                line = (TargetDataLine) AudioSystem.getLine(info);
                line.open(format);
                line.start();

                // 录制音频数据到内存
                byte[] buffer = new byte[4096];
                int bytesRead;

                System.out.println("录音开始...");
                while (recording && (bytesRead = line.read(buffer, 0, buffer.length)) != -1) {
                    audioData.write(buffer, 0, bytesRead);
                }

            } catch (LineUnavailableException e) {
                e.printStackTrace();
            } finally {
                line.close();
                System.out.println("录音已停止。");
            }
        }).start();
    }

    public void stopRecordingAndPlay() {
        if (!recording) {
            System.out.println("录音尚未开始。");
            return;
        }

        // 停止录音
        recording = false;

        // 播放录音
        new Thread(() -> {
            try {
                byte[] audioBytes = audioData.toByteArray();
                ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
                AudioFormat format = new AudioFormat(44100, 16, 2, true, true);
                DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
                SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
                line.open(format);
                line.start();

                System.out.println("正在播放录音...");
                byte[] buffer = new byte[4096];
                int bytesRead;

                while ((bytesRead = bais.read(buffer)) != -1) {
                    line.write(buffer, 0, bytesRead);
                }

                line.drain();
                line.close();
                System.out.println("录音播放结束。");

            } catch (IOException | LineUnavailableException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void sendRecording(String serverHost, int serverPort,String sender,String getter) {
        if (audioData == null || audioData.size() == 0) {
            System.out.println("没有录音数据可发送。");
            return;
        }


        new Thread(() -> {
            try {
                // 将录制的音频数据发送到服务器
                byte[] audioBytes = audioData.toByteArray();
                //构建message
                Message message = new Message();
                message.setMesType(MessageType.MESSAGE_GETCALL);
                message.setSender(sender);
                message.setGetter(getter);
                message.setSendTime(new Date().toString());//发送时间设置到message对象
                message.setVoiceData(audioBytes);

                //发送语音信息
                ObjectOutputStream oos =
                        new ObjectOutputStream(ManageClientConnectServerThread.getClientConnectServerThread(sender).getSocket().getOutputStream());
                oos.writeObject(message);
                oos.flush(); // 确保数据已经完全发送
                System.out.println("音频数据已发送。");

                //保存发出去的录音在本地
                ChatRoomGUI gui=ChatRoomGUI.getInstance();
                gui.historyMessages.add(message);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void stopRecording() {
        recording = false;
    }
}
